<template>
  <div class="app-container org">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <div>
        <p class="pinformation">搜索条件</p>
        <el-form label-width="auto" ref="queryRef" :model="queryParams">
          <el-row>
            <el-col :span="14">
              <el-form-item label="委托单位名称：" prop="wtCustomName">
                <el-input maxlength="100" clearable placeholder="请输入类别名称" v-model="queryParams.wtCustomName"
                  @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="报价人：" prop="createUserName">
                <el-input maxlength="100" clearable placeholder="请输入报价人" v-model="queryParams.createUserName"
                  @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item label="报价时间：">
                <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                  start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-row justify="end">
                <el-button type="success" @click="handleQuery">搜索</el-button>
                <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 机构列表盒子 -->
      <div>
        <el-row style="justify-content: space-between">
          <el-row>
            <p class="pinformation">报价单列表</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
          </el-row>
          <el-row style="padding-bottom: 5px; margin-left: 15px">
            <el-button link icon="plus" @click="handleAdd">新增</el-button>
          </el-row>
        </el-row>
        <el-table ref="mainTableRef" v-loading="loading" :show-overflow-tooltip="true" class="business"
          :data="quotationList" :row-class-name="tableRowClass" @row-click="rowClick">
          <el-table-column label="委托单位名称" align="center" prop="wtCustomName" width="160" />
          <el-table-column label="报价时间" align="center" prop="priceDate" width="100" />
          <el-table-column label="总价" align="center" prop="" />
          <el-table-column label="报价人" align="center" prop="createUserName" />
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button link @click.stop="handleCopy(scope.row)">引用</el-button><el-button link
                @click.stop="handleDel(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>
    <el-card class="rightCard">
      <el-form :model="form" label-width="110" ref="formRef" :rules="rules">
        <el-row>
          <el-col :span="10">
            <el-form-item label="项目名称：" prop="priceName">
              <el-input maxlength="100" clearable placeholder="请输入项目名称" v-model="form.priceName" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="报价单编号：" prop="params">
              <onlinePreview :typeId="serialTypeId" @emitForm="emitForm" ref="onlinePreviewRef" v-if="!form.priceCode">
              </onlinePreview>
              <span v-else>{{ form.priceCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-row justify="end">
              <el-button type="success" @click="handleStartFlow(false)">提交评审</el-button>
              <el-button type="success" @click="submitForm(false)">保存</el-button>
            </el-row>
          </el-col>
        </el-row>
        <p class="pinformation">委托单位信息</p>
        <el-row>
          <el-col :span="10">
            <el-form-item label="委托单位名称：" prop="wtCustomName">
              <el-autocomplete v-model="form.wtCustomName" :fetch-suggestions="wtQuerySearch" clearable maxlength="100"
                @select="autocompleteWtSelect" style="width: 100%" placeholder="请输入委托单位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="报价时间：" prop="">
              <el-date-picker v-model="form.priceDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择报价时间"
                :clearable="false" :editable="false"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="所在区域：" prop="wtAreaCode">
              <City @areaCode="wtAreaCode" :id="'right'" :viewForm="wtCityForm" @queryParam="queryParam" />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="详细地址：" prop="wtAddress">
              <el-input maxlength="100" clearable placeholder="请输入详细地址" v-model="form.wtAddress" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="东经（度）：" prop="wtJd">
              <el-input v-model="form.wtJd" placeholder="输入东经（度）" clearable maxlength="15">
                <template #suffix>
                  <el-icon class="el-input__icon" @click="editJdClick('form', 'wtJd')">
                    <Edit />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="北纬（度）：" prop="wtWd">
              <el-input v-model="form.wtWd" placeholder="输入北纬（度）" clearable maxlength="15">
                <template #suffix>
                  <el-icon class="el-input__icon" @click="editWdClick('form', 'wtWd')">
                    <Edit />
                  </el-icon>
                </template> </el-input></el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="联系人：" prop="wtContacts">
              <el-input maxlength="100" clearable placeholder="输入联系人" v-model="form.wtContacts" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="联系电话：" prop="wtPhonenumber" label-width="80">
              <el-input maxlength="100" clearable placeholder="请输入联系电话" v-model="form.wtPhonenumber" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="邮箱：" prop="wtEmail" label-width="50">
              <el-input maxlength="100" clearable placeholder="请输入邮箱" v-model="form.wtEmail" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <p class="pinformation">受检单位信息</p>
          <el-row style="padding-bottom: 5px; margin-left: 15px">
            <el-button size="small" type="success" @click="sameUnit">同委托单位</el-button>
          </el-row>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="受检单位名称：" prop="sjCustomName">
              <el-autocomplete v-model="form.sjCustomName" :fetch-suggestions="sjQuerySearch" clearable maxlength="100"
                @select="autocompleteSjSelect" style="width: 100%" placeholder="请输入委托单位名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="所在区域：" prop="sjAreaCode">
              <City @areaCode="sjAreaCode" :id="'right'" :viewForm="sjCityForm" />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="详细地址：" prop="sjAddress">
              <el-input maxlength="100" clearable placeholder="请输入详细地址" v-model="form.sjAddress" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="东经（度）：" prop="sjJd">
              <el-input v-model="form.sjJd" placeholder="输入东经（度）" clearable maxlength="15">
                <template #suffix>
                  <el-icon class="el-input__icon" @click="editJdClick('form', 'sjJd')">
                    <Edit />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="北纬（度）：" prop="sjWd">
              <el-input v-model="form.sjWd" placeholder="输入北纬（度）" clearable maxlength="15">
                <template #suffix>
                  <el-icon class="el-input__icon" @click="editJdClick('form', 'sjWd')">
                    <Edit />
                  </el-icon>
                </template> </el-input></el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="联系人：" prop="sjContacts">
              <el-input maxlength="100" clearable placeholder="输入联系人" v-model="form.sjContacts" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="联系电话：" prop="sjPhonenumber" label-width="80">
              <el-input maxlength="100" clearable placeholder="请输入联系电话" v-model="form.sjPhonenumber" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <p class="pinformation">搜索条件</p>
      <el-form :model="queryParamsRight" label-width="80" ref="queryRightRef">
        <el-row>
          <el-col :span="5">
            <el-form-item label="检测类别：" prop="jclbId">
              <el-select style="width: 100%" clearable filterable v-model="queryParamsRight.jclbId" placeholder="选择检测类别"
                :disabled="!priceId">
                <el-option v-for="item in proxy.addListNoLimit(
          jclbList,
          'jclbId',
          'jclbName'
        )" :key="item.jclbId" :value="item.jclbId" :label="item.jclbName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="点位名称：" prop="pointName" label-width="80">
              <el-input maxlength="100" clearable placeholder="请输入点位名称" v-model="queryParamsRight.pointName"
                @keyup.enter="handleQueryRight" :disabled="!priceId" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="周期：" prop="cycleType">
              <el-select style="width: 100%" clearable filterable v-model="queryParamsRight.cycleType"
                placeholder="请选择周期" :disabled="!priceId">
                <el-option v-for="dict in proxy.addListNoLimit(sys_point_cycle)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-row justify="center">
              <el-button type="success" @click="handleQueryRight" :disabled="!priceId">搜索</el-button>
              <el-button class="business resetBtn" @click="resetQueryRight" :disabled="!priceId">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <p class="pinformation">点位列表</p>
        <p class="totalStyle">共{{ totalRight }}条数据</p>
        <el-row style="padding-bottom: 5px; margin-left: 10px">
          <el-button link type="success" icon="Plus" @click="handleAddPoint">新增</el-button>
          <el-button link type="success" icon="Refresh" @click="handlePasteCustom">源自客户信息库</el-button>
          <el-button link type="success" icon="Refresh" @click="handleRenewCustom">更新客户信息库</el-button>
        </el-row>
      </el-row>
      <el-table v-loading="pointTableLoading" :data="pointList" ref="subTableRef">
        <el-table-column label="点位名称" align="center" prop="pointName" />
        <el-table-column label="检测类别" align="center" prop="jclbId">
          <template #default="scope">
            {{
          proxy.getItemByArray(
            jclbList,
            "jclbId",
            scope.row.jclbId,
            "jclbName"
          )
        }}
          </template>
        </el-table-column>
        <el-table-column label="连测天数" align="center" prop="sampleDay" />
        <el-table-column label="每天频次" align="center" prop="sampleCount" />
        <el-table-column label="周期" align="center" width="70px">
          <template #default="scope">
            <dict-tag :options="sys_point_cycle" :value="scope.row.cycleType" />
          </template>
        </el-table-column>
        <el-table-column label="周期次数" align="center" prop="cycleCount" />
        <el-table-column label="检测项目数" align="center" prop="jcxmCount" />
        <el-table-column label="分包项目数" align="center" prop="jcxmPCount" />
        <el-table-column label="操作" align="center" width="210px">
          <template #default="scope">
            <el-button link type="success" icon="EditPen" @click="handleEditPoint(scope.row)">编辑</el-button>
            <el-button link type="success" icon="CopyDocument" @click="handleCopyPoint(scope.row)">复制</el-button>
            <el-button link type="success" icon="Delete" @click="handlePointDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="totalRight > 0" :total="totalRight" v-model:page="queryParamsRight.pageNum"
        v-model:limit="queryParamsRight.pageSize" />
      <PointLocationDialog ref="PTDialogRef" :pointId="pointId" :queryPointList="getPoint" :primaryKeyId="priceId"
        @destroyPointDialog="destroyPointDialog" v-if="pointDialogDestroy" />
    </el-card>
    <el-dialog :class="'el-dialog-theme3'" v-model="jdDialog" title="修改经度" width="20%" draggable
      :close-on-click-modal="false">
      <el-form-item label="经度：">
        <el-row>
          <el-col :span="6">
            <el-input placeholder="度" maxlength="100" clearable v-model="jwdForm.degrees" />
          </el-col>
          <el-col :span="2" style="text-align: center"> 度 </el-col>
          <el-col :span="6">
            <el-input v-model="jwdForm.minutes" placeholder="分" maxlength="100" clearable />
          </el-col>
          <el-col :span="2" style="text-align: center"> 分 </el-col>
          <el-col :span="6">
            <el-input v-model="jwdForm.seconds" placeholder="秒" maxlength="100" clearable />
          </el-col>
          <el-col :span="2" style="text-align: center"> 秒 </el-col>
        </el-row>
      </el-form-item>
      <template #footer>
        <el-button type="success" @click="jdSave"> 保存 </el-button>
        <el-button @click="jdDialog = false" type="danger">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" v-model="wdDialog" title="修改纬度" width="20%" draggable
      :close-on-click-modal="false">
      <el-form-item label="纬度：" prop="deviceName">
        <el-row>
          <el-col :span="6">
            <el-input placeholder="纬度" maxlength="100" clearable v-model="jwdForm.degrees" />
          </el-col>
          <el-col :span="2" style="text-align: center"> 度 </el-col>
          <el-col :span="6">
            <el-input v-model="jwdForm.minutes" placeholder="分" maxlength="100" clearable />
          </el-col>
          <el-col :span="2" style="text-align: center"> 分 </el-col>
          <el-col :span="6">
            <el-input v-model="jwdForm.seconds" placeholder="秒" maxlength="100" clearable />
          </el-col>
          <el-col :span="2" style="text-align: center"> 秒 </el-col>
        </el-row>
      </el-form-item>
      <template #footer>
        <el-button type="success" @click="wdSave"> 保存 </el-button>
        <el-button @click="wdDialog = false" type="danger">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import City from "@/components/City/index.vue";
import onlinePreview from "@/components/onlinePreview/index.vue";
import useRouteView from "@/store/modules/routeView";
import { getCurrentUser, getLatestProcess } from "@/api/common";
import {
  getPriceList,
  postPriceInformation,
  getPriceForm,
  getPointList,
  delPrice,
  priceCopy,
  pasteCustomPoint,
  RenewCustomPoint,
} from "@/api/price/priceQuotation";
import { allListJclb } from "@/api/store/jclb";
import { delPoint, copyPoint } from "@/api/contract/taskPoint";
import { contractOption } from "@/api/contract/check";
import PointLocationDialog from "../../../contract/point/index";
import { getCustom } from "@/api/contract/custom";
import { getLatiAndLong, getDms, getCurrentTime } from "@/api/common";
const router = useRouter();

const routeViewStore = useRouteView();
const { proxy } = getCurrentInstance();
const { sys_point_cycle } = proxy.useDict("sys_point_cycle");
const loading = ref(false);
const loadingRight = ref(false);
const total = ref(0);
const totalRight = ref(0);
const queryParams = ref({ pageNum: 1, pageSize: 10 });
const queryParamsRight = ref({
  pageNum: 1,
  pageSize: 10,
  jclbId: -1,
  cycleType: -1,
});
const form = ref({ params: {} });
const quotationList = ref([]);
const dateRange = ref([]);
const pointList = ref([]);
const jclbList = ref([]);
const pointId = ref();
const serialTypeId = ref(300);
const pointTableLoading = ref(false);
const onlinePreviewRef = ref(null);
const rules = ref({
  priceName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
  wtJd: [
    {
      pattern:
        /^(((\d|[1-9]\d|1[1-7]\d|0)\.\d{0,6})|(\d|[1-9]\d|1[1-7]\d|0{1,3})|180\.0{0,6}|180)$/,
      message: "输入错误",
      trigger: "blur",
    },
  ],
  wtWd: [
    {
      pattern: /^([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/,
      message: "输入错误",
      trigger: "blur",
    },
  ],
  sjJd: [
    {
      pattern:
        /^(((\d|[1-9]\d|1[1-7]\d|0)\.\d{0,6})|(\d|[1-9]\d|1[1-7]\d|0{1,3})|180\.0{0,6}|180)$/,
      message: "输入错误",
      trigger: "blur",
    },
  ],
  sjWd: [
    {
      pattern: /^([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/,
      message: "输入错误",
      trigger: "blur",
    },
  ],
  wtPhonenumber: [
    {
      pattern: /^\d{11}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  sjPhonenumber: [
    {
      pattern: /^\d{11}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  wtEmail: [
    {
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
      message: "邮箱格式不符合规范",
      trigger: "blur",
    },
  ],
});

function getList() {
  return getPriceList(
    proxy.addDateRange(queryParams.value, dateRange.value)
  ).then((res) => {
    quotationList.value = res.rows;
    total.value = res.total;
    return quotationList.value[0]?.priceId;
  });
}

getCurrentTime().then((res) => {
  form.value.priceDate = res.data;
});

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  handleQuery();
}

function handleQueryRight() {
  queryParamsRight.value.pageNum = 1;
  getPoint();
}

function resetQueryRight() {
  proxy.resetForm("queryRightRef");
  handleQueryRight();
}

const priceId = ref("");

function rowClick(row) {
  return getPriceForm(row.priceId).then((response) => {
    priceId.value = row.priceId;
    form.value = response.data.price;
    pointList.value = response.data.taskPointList;
    totalRight.value = response.data.taskPointList.length;
    wtCityForm.value = {
      provinceCode: form.value.wtProvinceCode,
      cityCode: form.value.wtCityCode,
      areaCode: form.value.wtAreaCode,
    };
    sjCityForm.value = {
      provinceCode: form.value.sjProvinceCode,
      cityCode: form.value.sjCityCode,
      areaCode: form.value.sjAreaCode,
    };
    queryParamsRight.value.primaryId = row.priceId;
    heightBright.value = row.priceId;
    return;
  });
}

function getPoint() {
  loadingRight.value = true;
  getPointList(queryParamsRight.value).then((res) => {
    pointList.value = res.rows;
    totalRight.value = res.total;
    loadingRight.value = false;
  });
}

const heightBright = ref("");
function tableRowClass({ row }) {
  if (row) {
    if (row.priceId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}

allListJclb().then((res) => {
  jclbList.value = res.data;
});

function submitForm(isAuto) {
  return new Promise((resolve, reject) => {
    proxy.$refs["formRef"].validate((valid) => {
      if (!valid) {
        return false;
      }
      delete form.value.taskPointList;
      postPriceInformation(form.value).then((res) => {
        resolve();
        if (!isAuto) {
          proxy.$modal.msgSuccess("保存成功");
        }
        getList();
        heightBright.value = res.data;
        priceId.value = res.data;
        queryParamsRight.value.primaryId = res.data;
        form.value.priceId = res.data;
        if (!form.value.priceCode) {
          form.value.priceCode = form.value.params.serialData.maxCode;
        }
      });
    });
  });
}
 
function handleStartFlow() {
  submitForm(true).then((res) => {
      if (routeViewStore.routeView1) {
        proxy.$tab.closePage(routeViewStore.routeView1);
      }
      proxy.$modal.loading("正在启动流程中，请稍候...");
      getLatestProcess({ category: "15" }).then((res) => {
        proxy.$modal.closeLoading();
        if (res.data) {
          proxy.$tab.closePage().then(() => {
            router.push({
              path: "/flowable/task/record/index",
              query: {
                deployId: res.data.deploymentId,
                finished: true,
                path: "/price/priceQuotation",
                v_priceId: form.value.priceId,
              },
            });
          });
        } else {
          proxy.$modal.msgError("流程启动失败，未到找到相关流程！");
        }
      });
  });
}

function emitForm(val) {
  if (!form.value.params) form.value.params = {};
  form.value.params["serialData"] = val;
}

function handleAdd() {
  proxy.resetForm("formRef");
  proxy.resetForm("queryRightRef");
  heightBright.value = "";
  delete form.value.priceCode;
  delete form.value.priceId;
  delete form.value.wtProvinceCode;
  delete form.value.wtCityCode;
  delete form.value.sjProvinceCode;
  delete form.value.sjCityCode;
  wtCityForm.value = {};
  sjCityForm.value = {};
  priceId.value = "";
  pointList.value = [];
  totalRight.value = 0;
  getCurrentTime().then((res) => {
    form.value.priceDate = res.data;
  });
  nextTick(() => {
    onlinePreviewRef.value.reset();
    onlinePreviewRef.value.getList();
  });
}

getList();

// ----------------------------点位列表------------------------------

const pointDialogDestroy = ref(false);

function handleAddPoint() {
  submitForm(true).then((res) => {
    pointDialogDestroy.value = true;
    nextTick(() => {
      proxy.$refs["PTDialogRef"].form.primaryId = priceId.value;
      proxy.$refs["PTDialogRef"].isShowPTDialog = true;
    });
  });
}

function destroyPointDialog() {
  pointDialogDestroy.value = false;
  pointId.value = null;
}

function handleEditPoint(row) {
  pointDialogDestroy.value = true;
  nextTick(() => {
    proxy.$refs["PTDialogRef"].isShowPTDialog = true;
    pointId.value = row.pointId;
  });
}

function handleCopyPoint(row) {
  if(row.jcxmCount == 0){
    proxy.$modal.msgError("复制失败，当前点位还未添加检测项目！");
    return;
  }
  pointDialogDestroy.value = true;
  copyPoint(row.pointId).then((res) => {
    nextTick(() => {
      proxy.$refs["PTDialogRef"].isCopy = true;
      proxy.$refs["PTDialogRef"].isShowPTDialog = true;
      pointId.value = res.data;
    });
  });
}

function handlePointDel(row) {
  proxy.$modal
    .confirm(
      "删除该点位会将该点位下的点位信息及关联的检测项目信息全部删除，确定要删除吗？"
    )
    .then(async () => {
      await delPoint(row.pointId);
      proxy.$modal.msgSuccess("删除成功");
      getPoint();
    })
    .catch(() => { });
}

function handlePasteCustom() {
  submitForm(true).then((res) => {
    if (pointList.value.length > 0) {
      proxy.$modal
        .confirm(
          "当前点位列表已有信息，导入客户信息库污染源信息将覆盖当前列表所有信息，确定导入吗？"
        )
        .then(async () => {
          handleCustomPoint();
        })
        .catch(() => { });
    } else {
      handleCustomPoint();
    }
  });
}

function handleCustomPoint() {
  pasteCustomPoint(priceId.value).then((res) => {
    if (res.data == 0) {
      proxy.$modal.msgSuccess(res.msg);
    } else {
      proxy.$modal.msgWarning(res.msg);
    }
    getPoint();
  });
}

function handleRenewCustom() {
  if (pointList.value.length > 0) {
    proxy.$modal
      .confirm("更新点位列表已有信息，确定更新吗？")
      .then(async () => {
        handleRenewPoint();
      })
      .catch(() => { });
  } else {
    handleRenewPoint();
  }
}

function handleRenewPoint() {
  RenewCustomPoint(priceId.value).then((res) => {
    if (res.data == 0) {
      proxy.$modal.msgSuccess(res.msg);
    } else {
      proxy.$modal.msgWarning(res.msg);
    }
    getPoint();
  });
}

// ------------------------------------所在区域--------------------------------------------
const wtCityForm = ref({});
const sjCityForm = ref({});
function wtAreaCode(val) {
  form.value.wtAreaCode = val;
}
function sjAreaCode(val) {
  form.value.sjAreaCode = val;
}

const sameUnit = () => {
  form.value.sjCustomId = form.value.wtCustomId;
  form.value.sjCustomName = form.value.wtCustomName;
  form.value.sjAddress = form.value.wtAddress;
  form.value.sjContacts = form.value.wtContacts;
  form.value.sjPhonenumber = form.value.wtPhonenumber;
  form.value.sjJd = form.value.wtJd;
  form.value.sjWd = form.value.wtWd;
  form.value.sjAreaCode = form.value.wtAreaCode;
  sjCityForm.value = JSON.parse(JSON.stringify(cityInfor.value));
};

const cityInfor = ref({});
function queryParam(val) {
  cityInfor.value = val;
}

const wtQuerySearch = (querySearch, cb) => {
  let results = [];
  form.value.wtCustomId = "";
  contractOption({ customName: querySearch, pageName: 1, pageSize: 10 }).then(
    (res) => {
      results = res.rows.map((item) => {
        if (querySearch === item.customName) {
          form.value.wtCustomId = item.customId;
          form.value.wtContacts = item.contactsName;
          form.value.wtPhonenumber = item.contactsPhonenumber;
          form.value.wtEmail = item.email;
          form.value.wtAddress = item.address;
          wtCityForm.value = {
            provinceCode: item.provinceCode,
            cityCode: item.cityCode,
            areaCode: item.areaCode,
          };
          form.value.wtAreaCode = item.areaCode;
        }
        return { value: item.customName, customId: item.customId };
      });
      cb(results);
    }
  );
};

const sjQuerySearch = (querySearch, cb) => {
  let results = [];
  form.value.sjCustomId = "";
  contractOption({ customName: querySearch, pageName: 1, pageSize: 10 }).then(
    (res) => {
      results = res.rows.map((item) => {
        if (querySearch === item.customName) {
          form.value.sjCustomId = item.customId;
          form.value.sjContacts = item.contactsName;
          form.value.sjPhonenumber = item.contactsPhonenumber;
          form.value.sjEmail = item.email;
          form.value.sjAddress = item.address;
          sjCityForm.value = {
            provinceCode: item.provinceCode,
            cityCode: item.cityCode,
            areaCode: item.areaCode,
          };
          form.value.sjAreaCode = item.areaCode;
        }
        return { value: item.customName, customId: item.customId };
      });
      cb(results);
    }
  );
};

function autocompleteWtSelect(row) {
  form.value.wtCustomId = row.customId;
  getCustom(row.customId).then((res) => {
    form.value.wtContacts = res.data.contactsName;
    form.value.wtPhonenumber = res.data.contactsPhonenumber;
    form.value.wtEmail = res.data.email;
    form.value.wtAddress = res.data.address;
    form.value.wtJd = res.data.jd;
    form.value.wtWd = res.data.wd;
    wtCityForm.value = {
      provinceCode: res.data.provinceCode,
      cityCode: res.data.cityCode,
      areaCode: res.data.areaCode,
    };
    form.value.wtAreaCode = res.data.areaCode;
  });
}

function autocompleteSjSelect(row) {
  form.value.sjCustomId = row.customId;
  getCustom(row.customId).then((res) => {
    form.value.sjContacts = res.data.contactsName;
    form.value.sjPhonenumber = res.data.contactsPhonenumber;
    form.value.sjAddress = res.data.address;
    form.value.sjJd = res.data.jd;
    form.value.sjWd = res.data.wd;
    sjCityForm.value = {
      provinceCode: res.data.provinceCode,
      cityCode: res.data.cityCode,
      areaCode: res.data.areaCode,
    };
    form.value.sjAreaCode = res.data.areaCode;
  });
}

// --------------经纬度弹框操作-------------

const jwdForm = ref({});
const jdDialog = ref(false);
const wdDialog = ref(false);
const isJwd = ref("");
function jdSave() {
  if (
    !jwdForm.value.degrees &&
    !jwdForm.value.minutes &&
    !jwdForm.value.seconds
  ) {
    proxy.$modal.msgError("请填写完整的经度");
  } else {
    getLatiAndLong(jwdForm.value).then((res) => {
      form.value[isJwd.value] = res.data;
      jdDialog.value = false;
      isJwd.value = "";
    });
  }
}

function wdSave() {
  if (
    !jwdForm.value.degrees &&
    !jwdForm.value.minutes &&
    !jwdForm.value.seconds
  ) {
    proxy.$modal.msgError("请填写完整的纬度");
  } else {
    getLatiAndLong(jwdForm.value).then((res) => {
      form.value[isJwd.value] = res.data;
      wdDialog.value = false;
      isJwd.value = "";
    });
  }
}
function editJdClick(name, ruleName) {
  proxy.$refs[name + "Ref"].validateField(ruleName, (isOpen) => {
    if (isOpen) {
      jdDialog.value = true;
      isJwd.value = ruleName;
      if (form.value[ruleName]) {
        getDms({ jd: form.value[ruleName] }).then((res) => {
          jwdForm.value = res.data;
        });
      } else {
        jwdForm.value = {};
      }
    }
  });
}
function editWdClick(name, ruleName) {
  proxy.$refs[name + "Ref"].validateField(ruleName, (isOpen) => {
    if (isOpen) {
      wdDialog.value = true;
      isJwd.value = ruleName;
      if (form.value.ruleName) {
        getDms({ wd: form.value[ruleName] }).then((res) => {
          jwdForm.value = res.data;
        });
      } else {
        jwdForm.value = {};
      }
    }
  });
}

const heightParams = ref([
  { tableName: "main", bottomHeight: 45 },
  { tableName: "sub", bottomHeight: 74 },
]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [
        { tableName: "main", bottomHeight: 77 },
        { tableName: "sub", bottomHeight: 77 },
      ];
    } else {
      heightParams.value = [
        { tableName: "main", bottomHeight: 25 },
        { tableName: "sub", bottomHeight: 77 },
      ];
    }
    getTableHeight();
  }
);

// 左侧删除
function handleDel(scope) {
  proxy.$modal
    .confirm("确认要删除吗？")
    .then(async () => {
      await delPrice(scope.row.priceId);
      proxy.$modal.msgSuccess("删除成功");
      getList();
      handleAdd();
    })
    .catch(() => { });
}

function handleCopy(row) {
  proxy.$modal
    .confirm("确认要引用吗？")
    .then(() => {
      proxy.$modal.loading("正在引用，请稍候...");
      priceCopy(row.priceId).then((res) => {
        proxy.resetForm("queryRef");
        queryParams.value.priceId = res.data;
        getList().then((resPriceId) => {
          delete queryParams.value.priceId;
          rowClick({ priceId: resPriceId }).then(() => {
            proxy.$modal.closeLoading();
            proxy.$modal.msgSuccess("引用成功");
          });
        });
        //
        // form.value = response.data;
        // //
        // priceId.value = response.data.priceId;
        // queryParamsRight.value.primaryId = response.data.priceId;
        // //
        // pointList.value = response.data.taskPointList;
        // totalRight.value = response.data.taskPointList.length;
        // wtCityForm.value = {
        //   provinceCode: form.value.wtProvinceCode,
        //   cityCode: form.value.wtCityCode,
        //   areaCode: form.value.wtAreaCode,
        // };
        // sjCityForm.value = {
        //   provinceCode: form.value.sjProvinceCode,
        //   cityCode: form.value.sjCityCode,
        //   areaCode: form.value.sjAreaCode,
        // };
      });
    })
    .catch(() => { });
}

defineExpose({
  form,
});
</script>

<style scoped></style>
